#!/usr/bin/env python3
"""
归一化逻辑演示代码
展示Min-Max归一化的具体计算过程
"""

def normalize_scores_demo(results, score_key):
    """
    归一化逻辑演示版本
    """
    print(f"\n=== 归一化演示: {score_key} ===")
    
    if not results:
        print("结果为空，返回空字典")
        return {}
    
    # 提取分数
    scores = [r.get(score_key, 0.0) for r in results]
    print(f"原始分数: {scores}")
    
    # 找到最值
    min_score = min(scores)
    max_score = max(scores)
    print(f"最小分数: {min_score}")
    print(f"最大分数: {max_score}")
    print(f"分数范围: {max_score - min_score}")
    
    # 特殊情况处理
    if max_score - min_score < 1e-9:
        print("所有分数相同，返回1.0")
        return {i: 1.0 for i in range(len(results))}
    
    # 归一化计算
    normalized = {}
    print("\n归一化计算过程:")
    for i, score in enumerate(scores):
        norm_score = (score - min_score) / (max_score - min_score)
        normalized[i] = norm_score
        print(f"  索引{i}: ({score} - {min_score}) / ({max_score} - {min_score}) = {norm_score:.3f}")
    
    print(f"\n归一化结果: {normalized}")
    return normalized


def fusion_demo():
    """
    融合过程演示
    """
    print("\n" + "="*50)
    print("混合检索融合过程演示")
    print("="*50)
    
    # 模拟ES结果
    es_results = [
        {"id": "1", "_es_score": 15.2, "title": "Python工程师"},
        {"id": "2", "_es_score": 8.7, "title": "后端开发"},
        {"id": "3", "_es_score": 22.1, "title": "Python高级工程师"},
        {"id": "4", "_es_score": 12.3, "title": "Java工程师"}
    ]
    
    # 模拟ChromaDB结果
    chroma_results = [
        {"id": "1", "_similarity": 0.85, "title": "Python工程师"},
        {"id": "2", "_similarity": 0.72, "title": "后端开发"},
        {"id": "3", "_similarity": 0.91, "title": "Python高级工程师"},
        {"id": "5", "_similarity": 0.68, "title": "Python架构师"}
    ]
    
    print("\n1. ES结果:")
    for r in es_results:
        print(f"   {r['id']}: {r['title']} (分数: {r['_es_score']})")
    
    print("\n2. ChromaDB结果:")
    for r in chroma_results:
        print(f"   {r['id']}: {r['title']} (相似度: {r['_similarity']})")
    
    # 归一化
    es_norm = normalize_scores_demo(es_results, "_es_score")
    chroma_norm = normalize_scores_demo(chroma_results, "_similarity")
    
    # 融合计算
    print("\n3. 融合计算:")
    weight_es = 0.6
    weight_chroma = 0.4
    print(f"权重设置: ES={weight_es}, ChromaDB={weight_chroma}")
    
    # 收集所有岗位
    all_jobs = {}
    
    # 处理ES结果
    for i, job in enumerate(es_results):
        job_id = job["id"]
        all_jobs[job_id] = job.copy()
        all_jobs[job_id]["_es_normalized"] = es_norm.get(i, 0.0)
        all_jobs[job_id]["_es_original"] = job["_es_score"]
    
    # 处理ChromaDB结果
    for i, job in enumerate(chroma_results):
        job_id = job["id"]
        if job_id not in all_jobs:
            all_jobs[job_id] = job.copy()
        all_jobs[job_id]["_chroma_normalized"] = chroma_norm.get(i, 0.0)
        all_jobs[job_id]["_chroma_original"] = job["_similarity"]
    
    # 计算融合分数
    print("\n4. 融合分数计算:")
    fused_results = []
    for job_id, job in all_jobs.items():
        es_score = job.get("_es_normalized", 0.0)
        chroma_score = job.get("_chroma_normalized", 0.0)
        fused_score = weight_es * es_score + weight_chroma * chroma_score
        
        job["_fused_score"] = fused_score
        fused_results.append(job)
        
        print(f"   岗位{job_id}: {job['title']}")
        print(f"     ES归一化: {es_score:.3f}, ChromaDB归一化: {chroma_score:.3f}")
        print(f"     融合分数: {weight_es}×{es_score:.3f} + {weight_chroma}×{chroma_score:.3f} = {fused_score:.3f}")
        print()
    
    # 排序
    fused_results.sort(key=lambda x: x.get("_fused_score", 0.0), reverse=True)
    
    print("5. 最终排序结果:")
    for i, job in enumerate(fused_results, 1):
        print(f"   {i}. {job['title']} (融合分数: {job['_fused_score']:.3f})")


def edge_cases_demo():
    """
    边界情况演示
    """
    print("\n" + "="*50)
    print("边界情况演示")
    print("="*50)
    
    # 情况1: 所有分数相同
    print("\n1. 所有分数相同的情况:")
    same_scores = [
        {"id": "1", "_es_score": 5.0, "title": "岗位1"},
        {"id": "2", "_es_score": 5.0, "title": "岗位2"},
        {"id": "3", "_es_score": 5.0, "title": "岗位3"}
    ]
    normalize_scores_demo(same_scores, "_es_score")
    
    # 情况2: 空结果
    print("\n2. 空结果的情况:")
    empty_results = []
    normalize_scores_demo(empty_results, "_es_score")
    
    # 情况3: 只有一个结果
    print("\n3. 只有一个结果的情况:")
    single_result = [{"id": "1", "_es_score": 10.5, "title": "岗位1"}]
    normalize_scores_demo(single_result, "_es_score")


if __name__ == "__main__":
    print("归一化逻辑详细演示")
    print("="*50)
    
    # 基本归一化演示
    fusion_demo()
    
    # 边界情况演示
    edge_cases_demo()
    
    print("\n" + "="*50)
    print("演示完成！")
    print("="*50)
